import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

import { loginSsoLogoutInfo, loginSsoUserInfoApi } from '@/api/login';
import { mapStg, sessionStg } from '@/utils/storage';
// 定义初始状态接口，描述应用的布局状态
interface InitialStateType {
	token: string;
	isLogin: boolean;
	userInfo: Record<string, unknown>;
}

// 定义异步请求用户信息的 thunk
export const fetchUserInfo = createAsyncThunk<any, void>('user/fetchUserInfo', async () => {
	// 这里替换为实际的 API 请求代码
	const res = await loginSsoUserInfoApi();
	mapStg.set('userInfo', res.data);
	sessionStg.set('userInfo', res.data);
	return res.data;
});
export const fetchUserLogout = createAsyncThunk<any, void>('user/fetchUserLogout', async () => {
	// 这里替换为实际的 API 请求代码
	const res = await loginSsoLogoutInfo();
	return {
		success: true,
		data: res.data,
		code: res.data,
		errorMsg: res?.message ?? ''
	};
});

// 定义初始状态
const initialState: InitialStateType = {
	token: '',
	isLogin: false,
	userInfo: {}
};

// 创建应用状态切片
export const userSlice = createSlice({
	initialState,
	name: 'user',
	reducers: {
		/** 设置token */
		setToken: (state, { payload }: { payload: string }) => {
			state.token = payload;
		},
		/** 设置用户信息 */
		setUserInfo: (state, { payload }: { payload: Record<string, unknown> }) => {
			state.userInfo = payload;
		},
		/** 设置登录状态 */
		setIsLogin: (state, { payload }: { payload: boolean }) => {
			state.isLogin = payload;
		},
		/** 退出登录 */
		setLogoutOut: state => {
			state.userInfo = {};
			state.token = '';
			state.isLogin = false;
			sessionStg.clear();
			mapStg.clear();
		}
	},
	extraReducers: builder => {
		builder.addCase(fetchUserInfo.fulfilled, (state, action) => {
			state.userInfo = action.payload;
		});
		builder.addCase(fetchUserLogout.fulfilled, (state, action) => {
			if (action.payload.success) {
				state.userInfo = {};
				state.token = '';
				state.isLogin = false;
				sessionStg.clear();
				mapStg.clear();
			}
		});
	},
	selectors: {
		getToken: state => state.token,
		getUserInfo: state => state.userInfo,
		getIsLogin: state => state.isLogin
	}
});

export const { setToken, setUserInfo, setLogoutOut, setIsLogin } = userSlice.actions;

export const { getToken, getUserInfo, getIsLogin } = userSlice.selectors;
